package com.hitcoder.chat.utils

import android.content.Context
import android.media.AudioAttributes
import android.media.AudioManager
import android.media.MediaPlayer
import android.net.Uri
import android.util.Log
import com.hitcoder.chat.model.PlayMode
import java.io.IOException

/**
 * 音乐播放管理类
 * Created by Administrator on 2015/8/27 0027.
 */
class PlayerManager private constructor(private val context: Context) {

    companion object {

        private lateinit var playerManager: PlayerManager

        fun getManager(context: Context): PlayerManager {
            if (!this::playerManager.isInitialized) {
                synchronized(PlayerManager::class.java) { playerManager = PlayerManager(context) }
            }
            return playerManager
        }
    }

    init {
        initMediaPlayer()
        initAudioManager()
    }

    private var audioManager: AudioManager? = null
    private var mediaPlayer: MediaPlayer? = null
    private var callback: PlayCallback? = null
    var isPause = false
        private set
    private var currentMode = PlayMode.MODE_SPEAKER

    /**
     * 初始化播放器
     */
    private fun initMediaPlayer() {
        mediaPlayer = MediaPlayer()
        //默认设置为通话音量
        val attributes = AudioAttributes.Builder()
            .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
            .setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION)
            .build()
        mediaPlayer?.setAudioAttributes(attributes)
    }

    /**
     * 初始化音频管理器
     */
    private fun initAudioManager() {
        audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
        audioManager?.mode = AudioManager.MODE_IN_COMMUNICATION
        audioManager?.isSpeakerphoneOn = true //默认为扬声器播放
    }

    /**
     * 播放回调接口
     */
    interface PlayCallback {
        /**
         * 音乐准备完毕
         */
        fun onPrepared()

        /**
         * 音乐播放完成
         */
        fun onComplete()

        /**
         * 音乐停止播放
         */
        fun onStop()
        fun onPause(msec: Int)
    }

    /**
     * 播放音乐
     *
     * @param path     音乐文件路径
     * @param callback 播放回调函数
     */
    fun play(path: String?, callback: PlayCallback) {
        this.callback = callback
        try {
            mediaPlayer!!.reset()
            mediaPlayer!!.setDataSource(context, Uri.parse(path))
            mediaPlayer!!.prepareAsync()
            mediaPlayer!!.setOnPreparedListener {
                callback.onPrepared()
                mediaPlayer!!.start()
            }
            mediaPlayer!!.setOnCompletionListener {
                resetPlayMode()
                callback.onComplete()
            }
            mediaPlayer!!.setOnErrorListener { mp, what, extra ->
                resetPlayMode()
                callback.onComplete()
                true
            }
            mediaPlayer!!.setOnSeekCompleteListener { mediaPlayer!!.start() }
        } catch (e: IOException) {
            Log.i(PRINT_STACK_TRACE, "PlayerManager play Exception " + e.message)
        }
    }

    fun pause() {
        if (isPlaying) {
            isPause = true
            mediaPlayer!!.pause()
            callback!!.onPause(mediaPlayer!!.currentPosition)
        }
    }

    fun resume() {
        if (isPause) {
            isPause = false
            mediaPlayer!!.start()
        }
    }

    fun resume(msec: Int) {
        if (isPause) {
            isPause = false
            mediaPlayer!!.seekTo(msec)
        }
    }

    /**
     * 获取当前播放模式
     *
     * @return
     */
    var mode: PlayMode
        get() = currentMode
        set(mode) {
            if (mode === PlayMode.MODE_EARPIECE) {
                changeToEarpieceMode()
            } else if (mode === PlayMode.MODE_HEADSET) {
                changeToHeadsetMode()
            } else {
                changeToSpeakerMode()
            }
        }

    /**
     * 切换到听筒模式
     */
    private fun changeToEarpieceMode() {
        currentMode = PlayMode.MODE_EARPIECE
        audioManager!!.isSpeakerphoneOn = false
        audioManager!!.setStreamVolume(
            AudioManager.STREAM_MUSIC,
            audioManager!!.getStreamMaxVolume(AudioManager.MODE_IN_COMMUNICATION),
            AudioManager.FX_KEY_CLICK
        )
    }

    /**
     * 切换到耳机模式
     */
    private fun changeToHeadsetMode() {
        currentMode = PlayMode.MODE_HEADSET
        audioManager!!.isSpeakerphoneOn = false
    }

    /**
     * 切换到外放模式
     */
    private fun changeToSpeakerMode() {
        currentMode = PlayMode.MODE_SPEAKER
        audioManager!!.isSpeakerphoneOn = true
    }

    fun resetPlayMode() {
        if (audioManager!!.isWiredHeadsetOn) {
            changeToHeadsetMode()
        } else {
            changeToSpeakerMode()
        }
    }

    /**
     * 调大音量
     */
    fun upVoice() {
        val currentVolume = audioManager!!.getStreamVolume(AudioManager.STREAM_MUSIC)
        if (currentVolume < audioManager!!.getStreamMaxVolume(AudioManager.STREAM_MUSIC)) {
            audioManager!!.adjustStreamVolume(
                AudioManager.STREAM_MUSIC,
                AudioManager.ADJUST_RAISE, AudioManager.FX_FOCUS_NAVIGATION_UP
            )
        }
    }

    /**
     * 调小音量
     */
    fun downVoice() {
        val currentVolume = audioManager!!.getStreamVolume(AudioManager.STREAM_MUSIC)
        if (currentVolume > 0) {
            audioManager!!.adjustStreamVolume(
                AudioManager.STREAM_MUSIC,
                AudioManager.ADJUST_LOWER, AudioManager.FX_FOCUS_NAVIGATION_UP
            )
        }
    }

    /**
     * 停止播放
     */
    fun stop() {
        if (isPlaying) {
            try {
                mediaPlayer!!.stop()
                callback!!.onStop()
            } catch (e: IllegalStateException) {
                Log.i(PRINT_STACK_TRACE, "PlayerManager stop Exception " + e.message)
            }
        }
    }

    /**
     * 是否正在播放
     *
     * @return 正在播放返回true, 否则返回false
     */
    val isPlaying: Boolean
        get() = mediaPlayer != null && mediaPlayer!!.isPlaying


}